package com.ry.core.base.dao.hibernate;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.Map;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.ry.core.base.model.SimpleModel;
import com.ry.core.exception.DaoException;
import com.ry.core.util.ObjectUtils;

/**
 * hibernate接口默认实现类
 * 
 * @author lqw
 * 
 */
public class HibernateDaoImpl extends HibernateDaoSupport implements
		HibernateDao {

	public static Logger logger = Logger.getLogger(HibernateDaoImpl.class);

	@Override
	public void add(SimpleModel entity) throws DaoException {
		try {
			getHibernateTemplate().save(entity);
		} catch (Exception ex) {
			throw new DaoException("新增失败", ex);
		}
	}

	@Override
	public SimpleModel edit(SimpleModel entity) throws DaoException {
		try {
			getHibernateTemplate().merge(entity);
			getHibernateTemplate().flush();
			getHibernateTemplate().clear();// 清空缓存，否则从缓存拿出对象
			return getHibernateTemplate()
					.get(entity.getClass(), entity.getId());
		} catch (Exception ex) {
			throw new DaoException("修改失败", ex);
		}
	}

	@Override
	public SimpleModel editObj(SimpleModel entity) throws DaoException {
		try {
			Map<String, Object> m = ObjectUtils.getFiledNotNullValues(entity);
			String objName = entity.getClass().getName();
			String hql = "update " + objName + " set ";
			Object v[] = new Object[m.size()];
			int i = 0;
			for (String k : m.keySet()) {
				hql += k + "=?,";
				v[i++] = m.get(k);
			}
			if (m.size() > 0) {
				hql = hql.substring(0, hql.length() - 1);
			}
			hql += " where id='" + entity.getId() + "'";
			getHibernateTemplate().bulkUpdate(hql, v);
			// getHibernateTemplate().flush();
			// getHibernateTemplate().clear();// 清空缓存，否则从缓存拿出对象
			return getHibernateTemplate()
					.get(entity.getClass(), entity.getId());
		} catch (Exception ex) {
			throw new DaoException("修改失败", ex);
		}
	}

	@Override
	public void remove(SimpleModel entity) throws DaoException {
		try {
			getHibernateTemplate().delete(entity);
		} catch (Exception ex) {
			throw new DaoException("删除失败", ex);
		}
	}

	@Override
	public HibernateTemplate getTemplate() throws DaoException {
		try {

			return getHibernateTemplate();
		} catch (Exception ex) {
			throw new DaoException("模板获取失败", ex);
		}
	}

	/**
	 * 根据主键取对象
	 * 
	 * @param theClass
	 * @param pk
	 * @return
	 * @throws DaoException
	 */
	public SimpleModel get(Class<?> theClass, String id) throws DaoException {
		try {
			return (SimpleModel) this.getHibernateTemplate().get(theClass, id);
		} catch (DataAccessException ex) {
			throw new DaoException("查找对象失败" + ex.getMessage(), ex);
		}
	}

	/**
	 * 判断当前对象是否存在
	 * 
	 * @param theClass
	 * @param pk
	 * @return
	 */
	public boolean isExist(Class<?> theClass, Serializable pk) {
		String countHQL = "select count(*) from " + theClass.getName()
				+ "  bo where bo.id = '" + pk + "'";
		return this.queryCount(countHQL) > 0;
	}

	/**
	 * 获取记录数
	 * 
	 * @param countHQL
	 * @return
	 */
	public int queryCount(final String countHQL) {
		return ((Long) this.getHibernateTemplate().execute(
				new HibernateCallback<Object>() {
					public Object doInHibernate(Session session)
							throws HibernateException {
						try {
							Query query = session.createQuery(countHQL);
							Object temp = query.uniqueResult();
							if (temp != null) {
								return (Long) temp;
							}
							return 0;
						} catch (HibernateException e) {
							logger.debug("", e);
						}
						return 0;
					}
				})).intValue();
	}

}
